package broker;

import java.io.*;
import java.net.*;
import java.util.UUID;
import util.IProtocol;

/**
 * BrokerClient.
 */
public class BrokerClient {
     final String host;
     
     final int    	port;      
     Socket 		broker;
     String 		status;     
     String 		id;     
     PrintWriter 	toBroker;
     BufferedReader fromBroker;
     
     public String getID() {return id;}
     
     public String getStatus() {return status;}
     
     public BufferedReader getBrokerInput() {return fromBroker;}

     public PrintWriter getBrokerOutput() {return toBroker;}
     
     public BrokerClient(String brokerHost, int brokerPort){
     	 this.host = brokerHost;
     	 this.port = brokerPort;
     }
     
 	/**
 	 * Generate a statistically unique identifier.
 	 *  
 	 * Stored in idStorage
 	 */
 	public static String generateID() {
 		return UUID.randomUUID().toString();
 	}
     
 	public boolean connect() {
 		
		try {
			broker = 	new Socket (host, port);
			toBroker = 	new PrintWriter (broker.getOutputStream(), true);
			fromBroker = new BufferedReader (new InputStreamReader(broker.getInputStream()));
			
		} catch (IOException ioe) {
			return false;
		}
		
		id = generateID();
		toBroker.println(IProtocol.loginMsg + IProtocol.separator + id);
		
		try {
			status = fromBroker.readLine();
		} catch (IOException e) {
			System.err.println("Unable to retrieve status from broker.");
			return false;
		}
		return true;
 	}
 	
	/** 
	 * Terminate connection to broker. 
	 */
	public void shutdown() {
		try {
			if (broker != null) {
				broker.close();
			}
		} catch (IOException e) {
			System.out.println("Unable to terminate broker connection");
		}
	}
}
